package org.ideo.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.config.Result;
import org.apache.struts2.config.Results;
import org.apache.struts2.dispatcher.ServletDispatcherResult;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.ideo.model.User;
import org.ideo.service.UserManager;


@Results({
	@Result(name="success", type=ServletDispatcherResult.class, value="Member.jsp"),
	@Result(name="input", type=ServletDispatcherResult.class, value="Login.jsp")
})
public class LoginAction implements ServletRequestAware {

    private String username;
    private String password;
    private String message;

    private User user;
    
    private UserManager userManager;
    
    private HttpServletRequest request;
    
    public String execute() {
    
    	if (isInvalid(username) || isInvalid(password)) 
        	return "input";
    	
    	user = userManager.findUser(username, password);
        
        if ( user != null) {
        	request.getSession(true).setAttribute("user", user);    	
        	return "success";
        } else {
        	message = "loginError";
        	return "input";
        }
    }

    private boolean isInvalid(String value) {
        return (value == null || value.length() == 0);
    }

    public void setServletRequest(HttpServletRequest httpServletRequest) {
    	request = httpServletRequest;
    }

    public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

}
